package com.liuyk.commonlib.network;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

import com.liuyk.commonlib.utility.FileUtils;

import java.io.File;

/**
 * 用与下载普通文件，下载完成后，不做任何处理
 * <p>
 * Created by liuyakui on 2020-02-07.
 */
public class DownloadServer extends Service implements DownloadCallBack {

    private String mUrl;
    private String mFileName;

    private final MyBinder binder = new MyBinder();

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        mUrl = intent.getStringExtra("fileUrl");
        mFileName = intent.getStringExtra("fileName");
        File file = new File(FileUtils.getFileDir(), mFileName);
        DownloadManager.getInstance().download(mUrl, true, file, this);
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void downloadFail(String url, String reason) {
        DownloadNotifyManager.getInstance(getApplicationContext()).updateNotify(
                mUrl, mFileName, "下载失败，点击重试");
        DownloadNotifyManager.getInstance(getApplicationContext()).clickRetry(getApplicationContext());
    }

    @Override
    public void downloading(String url, long length, long progress, int percent) {
        if (length > 0) {
            DownloadNotifyManager.getInstance(getApplicationContext()).updateProgress(
                    mUrl, mFileName, length, progress);
        }
    }

    @Override
    public void downloadSuccess(String url, File file) {
        DownloadNotifyManager.getInstance(getApplicationContext()).updateNotify(
                mUrl, mFileName, "下载完成");
        stopSelf();
    }

    private class MyBinder extends Binder {
        public DownloadServer getService() {
            return DownloadServer.this;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
